import React, { useEffect, useState } from "react";
import userApi, { User } from "../../api/user-api";

const GetDataComponent = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setLoading] = useState(false);
  const [error, setError] = useState("");

  // 加载数据
  useEffect(() => {
    setLoading(true);
    const { request, cancel } = userApi.getAll<User>();
    request
      .then((res) => {
        const { data, status } = res;
        if (status === 200) {
          setLoading(false);
          setUsers(data);
        }
      })
      .catch((err) => {
        setLoading(false);
        setError(err.message);
      });
  }, []);

  // 删除
  const deletUser = (id: number) => {
    // 先删除数组
    setUsers(users.filter((item) => item.id !== id));
    // 发送删除请求
    userApi.delete(id);
  };

  // 修改
  const updateUser = (user: User) => {
    let obj = {
      name: "123",
      username: "456",
      title: "789",
      id: user.id,
    };
    const tempUsers = users.filter((item) => item.id !== user.id);
    // 新增数据
    tempUsers.push(obj);
    setUsers(tempUsers);
    // 发送删除请求
    userApi.update(obj);
  };

  // 新增
  const createUser = () => {
    let obj = {
      name: "123",
      username: "456",
      title: "789",
      id: 2222,
    };
    setUsers([...users, obj]);
    // 发送删除请求
    userApi.create(obj);
  };

  return (
    <div>
      {error && <p className="text-danger">{error}</p>}
      {isLoading && <div className="spinner-border"></div>}
      <button className="btn btn-warning mt-5" onClick={() => createUser()}>
        新增
      </button>
      <table className="table">
        <thead>
          <tr>
            <th scope="col">id</th>
            <th scope="col">name</th>
            <th scope="col">username</th>
            <th scope="col">email</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map((item) => {
            return (
              <tr key={item.id}>
                <th scope="row">{item.id}</th>
                <td>{item.name}</td>
                <td>{item.username}</td>
                <td>@{item.email}</td>
                <td>
                  <button
                    className="btn btn-success mx-2"
                    onClick={() => updateUser(item)}
                  >
                    修改
                  </button>
                  <button
                    className="btn btn-danger"
                    onClick={() => deletUser(item.id)}
                  >
                    删除
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

export default GetDataComponent;
